package com.audi.box.service;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.IntentService;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Message;
import android.util.Log;

import com.audi.BaseActivity;
import com.audi.activity.HomeControlActivity;
import com.audi.adapter.ListDeviceCardAdapterTop;
import com.audi.box.objects.Authen;
import com.audi.box.objects.Devicestatus;
import com.audi.box.objects.LocalData;
import com.audi.box.objects.OJResponsive;
import com.audi.box.server.TCPClient;
import com.audi.dto.DeviceItem;
import com.audi.handler.JSonparse;
import com.audi.message.ActionMessage;
import com.audi.message.SendMessage;
import com.audi.view.Customdialog;
import com.google.gson.JsonObject;

public class ConnectService extends IntentService   {
	private ProgressDialog pDialog;
	private String Login2 ="login2";
	public ConnectService() {
		super("ConnectService");
		// TODO Auto-generated constructor stub
	}
	public static TCPClient mmTcpClient;
	private static TCPClient mTcpClient;
	String TAG1="Connectservice";
	String Tag2="SigninActivity";
//	String hostip ="192.168.3.103";
	public static SendMessage sendMessage = new SendMessage();
	public static Activity mActivity;
//	String hostip ="192.168.11.106";
//	String hostip ="172.16.10.37";
	String hostip ="192.168.0.185";
	int hostport =11008;

	 @Override
		protected void onHandleIntent(Intent intent) {
	     try
	     {		
	    	 Log.d(TAG1,"Services started-2");
	    	 new connectTask().execute("");	    	
	     }
	     catch(Exception e)
	     {
	    	 Log.e(TAG1,"faile to excute connecttask-2"+e);
	     }
	   }
	 public class connectTask extends AsyncTask<String,String,TCPClient> {
		 
	        @Override
	        protected TCPClient doInBackground(String... message) {
	        	Log.d(TAG1,"connectTask - in asycn task- 3");
	            //we create a TCPClient object and
	            mmTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
	                @Override
	                //here the messageReceived method is implemented
	                public void messageReceived(String message) {
	                    //this method calls the onProgressUpdate
	                	Log.d(TAG1,"connectTask - in asycn task- 4");
	                    publishProgress(message);
	                }
	            });
	            if (LocalData.isConnectsuccess == false)
	            {
	            try {
	            	
	            	 Log.d(TAG1,"connectTask - in asycn task- 5");	            	
//	 	              mmTcpClient.run(LocalData.strIP,LocalData.strport);
//	 	             mmTcpClient.run("172.16.10.37", 44444);
	 	            mmTcpClient.run(LocalData.strIP, LocalData.strport);
	            Log.d(TAG1,"Services started - in asycn task- 6");
	            }
	            catch (Exception e)
	            {
	            	Log.e(TAG1,""+e);
	            }
	            }
	            return null;
	        }
	 
	        @Override
	        protected void onProgressUpdate(final String... values) {
	            super.onProgressUpdate(values); 
	            Log.e(TAG1,"Onprogressupdate" + values[0]);
	            LocalData.strreceiver = values[0];
	            Authen mOJResponsive = new Authen();
	            Devicestatus mDevicestatus = new Devicestatus();
	            mDevicestatus = JSonparse.getdevicestatus(LocalData.strreceiver);
	            if (mDevicestatus!=null)
	            {	Log.d("Change device status","1" + mDevicestatus.getDv0());
//	            	if (mDevicestatus.getDv0()!=null) 
//	            	{	Log.d("Change device status","2" + mDevicestatus.getDv0());
//	            		if (mDevicestatus.getDv0() == true)
//	            		{	
////	            			Log.d("Change device status","3" + mDevicestatus.getDv0());
////	            		try{
////	            			DeviceItem newItemOpen = new DeviceItem();
////	            			Log.d("Change device status","Device ID: " + HomeControlActivity.mListDeviceMemberTop.get(0).getDeviceId() + " Name: " + HomeControlActivity.mListDeviceMemberTop.get(0).getDeviceName());
////							newItemOpen.setDeviceId(HomeControlActivity.mListDeviceMemberTop.get(0).getDeviceId());
////							newItemOpen.setDeviceStatus(1);
////							sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
////									newItemOpen, ListDeviceCardAdapterTop.handlerUpdateDevice);
////							Log.d("Change device status","End set: " + newItemOpen.getDeviceId() + " Name:" + newItemOpen.getDeviceName());
////	            		}
////	            		catch(Exception e)
////	            		{
////	            			Log.e("Change device status","failed: " + e);}
//	            			opendevice(true,0);
//	            		}
//	            		else 
//	            		{	
////	            			Log.d("Change device status","8" + mDevicestatus.getDv0());
////	            		DeviceItem newItemOpen = new DeviceItem();
////            			Log.d("Change device status","Device ID: " + HomeControlActivity.mListDeviceMemberTop.get(0).getDeviceId() + " Name: " + HomeControlActivity.mListDeviceMemberTop.get(0).getDeviceName());
////						newItemOpen.setDeviceId(HomeControlActivity.mListDeviceMemberTop.get(0).getDeviceId());
////						newItemOpen.setDeviceStatus(0);
////						sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
////								newItemOpen, ListDeviceCardAdapterTop.handlerUpdateDevice);
//	            			opendevice(false,0);
//	            		}
//	            	}
	           ///////////////////device 2/////////////////////
	            	if (mDevicestatus.getDv1()!=null) 
	            	{	Log.d("Change device status","2" + mDevicestatus.getDv1());
	            		if (mDevicestatus.getDv1() == true)
	            		{	
//	            			Log.d("Change device status","3" + mDevicestatus.getDv1());
//	            		try{
//	            			DeviceItem newItemOpen = new DeviceItem();
//	            			Log.d("Change device status","Device ID: " + HomeControlActivity.mListDeviceMemberTop.get(1).getDeviceId() + " Name: " + HomeControlActivity.mListDeviceMemberTop.get(1).getDeviceName());
//							newItemOpen.setDeviceId(HomeControlActivity.mListDeviceMemberTop.get(1).getDeviceId());
//							newItemOpen.setDeviceStatus(1);
//							sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
//									newItemOpen, ListDeviceCardAdapterTop.handlerUpdateDevice);
//							Log.d("Change device status","End set: " + newItemOpen.getDeviceId() + " Name:" + newItemOpen.getDeviceName());
//	            		}
//	            		catch(Exception e)
//	            		{
//	            			Log.e("Change device status","failed: " + e);}
	            			opendevice(true,1);
	            		}
	            		else 
	            		{	
//	            		Log.d("Change device status","8" + mDevicestatus.getDv1());
//	            		DeviceItem newItemOpen = new DeviceItem();
//            			Log.d("Change device status","Device ID: " + HomeControlActivity.mListDeviceMemberTop.get(1).getDeviceId() + " Name: " + HomeControlActivity.mListDeviceMemberTop.get(1).getDeviceName());
//						newItemOpen.setDeviceId(HomeControlActivity.mListDeviceMemberTop.get(1).getDeviceId());
//						newItemOpen.setDeviceStatus(0);
//						sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
//								newItemOpen, ListDeviceCardAdapterTop.handlerUpdateDevice);
	            			opendevice(false,2);
	            		}
	            	}
	///////////////////device 3/////////////////////
		            	if (mDevicestatus.getDv2()!=null) 
		            	{	Log.d("Change device status","2" + mDevicestatus.getDv2());
		            		if (mDevicestatus.getDv2() == true)
		            		{	
//		            			Log.d("Change device status","3" + mDevicestatus.getDv2());
//		            		try{
//		            			DeviceItem newItemOpen = new DeviceItem();
//		            			Log.d("Change device status","Device ID: " + HomeControlActivity.mListDeviceMemberTop.get(2).getDeviceId() + " Name: " + HomeControlActivity.mListDeviceMemberTop.get(2).getDeviceName());
//								newItemOpen.setDeviceId(HomeControlActivity.mListDeviceMemberTop.get(2).getDeviceId());
//								newItemOpen.setDeviceStatus(1);
//								sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
//										newItemOpen, ListDeviceCardAdapterTop.handlerUpdateDevice);
//								Log.d("Change device status","End set: " + newItemOpen.getDeviceId() + " Name:" + newItemOpen.getDeviceName());
//		            		}
//		            		catch(Exception e)
//		            		{
//		            			Log.e("Change device status","failed: " + e);}
		            			opendevice(true,2);
		            		}
		            		else 
		            		{	
//		            		Log.d("Change device status","8" + mDevicestatus.getDv2());
//		            		DeviceItem newItemOpen = new DeviceItem();
//	            			Log.d("Change device status","Device ID: " + HomeControlActivity.mListDeviceMemberTop.get(1).getDeviceId() + " Name: " + HomeControlActivity.mListDeviceMemberTop.get(1).getDeviceName());
//							newItemOpen.setDeviceId(HomeControlActivity.mListDeviceMemberTop.get(2).getDeviceId());
//							newItemOpen.setDeviceStatus(0);
//							sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
//									newItemOpen, ListDeviceCardAdapterTop.handlerUpdateDevice);
		            			opendevice(false,2);
		            		}
		            	}
		///////////////////device 3/////////////////////
				            	if (mDevicestatus.getDv3()!=null) 
				            	{	Log.d("Change device status","2" + mDevicestatus.getDv3());
				            		if (mDevicestatus.getDv3() == true)
				            		{	
//				            			Log.d("Change device status","3" + mDevicestatus.getDv3());
//				            		try{
//				            			DeviceItem newItemOpen = new DeviceItem();
//				            			Log.d("Change device status","Device ID: " + HomeControlActivity.mListDeviceMemberTop.get(3).getDeviceId() + " Name: " + HomeControlActivity.mListDeviceMemberTop.get(3).getDeviceName());
//										newItemOpen.setDeviceId(HomeControlActivity.mListDeviceMemberTop.get(3).getDeviceId());
//										newItemOpen.setDeviceStatus(1);
//										sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
//												newItemOpen, ListDeviceCardAdapterTop.handlerUpdateDevice);
//										Log.d("Change device status","End set: " + newItemOpen.getDeviceId() + " Name:" + newItemOpen.getDeviceName());
//				            		}
//				            		catch(Exception e)
//				            		{
//				            			Log.e("Change device status","failed: " + e);}
				            			opendevice(true,3);
				            		}
				            		else 
				            		{	
//				            		Log.d("Change device status","8" + mDevicestatus.getDv3());
//				            		DeviceItem newItemOpen = new DeviceItem();
//			            			Log.d("Change device status","Device ID: " + HomeControlActivity.mListDeviceMemberTop.get(1).getDeviceId() + " Name: " + HomeControlActivity.mListDeviceMemberTop.get(3).getDeviceName());
//									newItemOpen.setDeviceId(HomeControlActivity.mListDeviceMemberTop.get(3).getDeviceId());
//									newItemOpen.setDeviceStatus(0);
//									sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
//											newItemOpen, ListDeviceCardAdapterTop.handlerUpdateDevice);
				            			opendevice(false,3);
				            		}
				            	}		         
	            }
	            
	            mOJResponsive = check_tag(LocalData.strreceiver);
	            Log.d(Login2,mOJResponsive.getTag()+" | "+mOJResponsive.getMess()+" | "+mOJResponsive.getUser_group()+mOJResponsive.getUser_name());
//	            if (mOJResponsive.getTag()=="login")
	            Log.d(TAG1,"Tag: "+mOJResponsive.getTag());
	            
	            try{
	            	if (mOJResponsive.getTag().equals(LocalData.TAG_CHECKBOX))
		            {	
	            		Log.d("Checkbox","TAG checkbox");
		            	if (mOJResponsive.getSuccess()==true)
		            	{
		            		Log.d("Checkbox","checkbox = true");
		            	}
		            	else 
		            	{	Log.d("Checkbox","Checkbox = false");
		            		opendevice(false,0);
		            		opendevice(false,1);
		            		opendevice(false,2);
		            		opendevice(false,3);
		            		Intent intt = new Intent(ConnectService.this, Customdialog.class);
				            intt.putExtra("mess", "Box Android hiện không kết nối với Server");
				            intt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
				           startActivity(intt);
		            		}
		            }
	            	if (mOJResponsive.getTag().equals(LocalData.TAG_LOGIN))
	            {	
	    	            Log.d(Login2,"inside if");
	            	if (mOJResponsive.getSuccess()==true)
	            	{
	            		LocalData.islogin = true;
	            		Log.d(Login2,"login true");
	            	}
	            	else 
	            	{
	            		LocalData.islogin=false;
	            		Log.d(Login2,"False");
	            		}
	            }
	            	//changepass
	            	if (mOJResponsive.getTag().equals(LocalData.TAG_CHANGEPASS))
		            {	
		    	            Log.d(LocalData.TAG_CHANGEPASS,"inside if" + mOJResponsive.getSuccess());
		            	if (mOJResponsive.getSuccess()==true)
		            	{
		            		LocalData.ischangedpass = true;
		            		Log.d(LocalData.TAG_CHANGEPASS,"changepass true");
		            	}
		            	else 
		            	{
		            		LocalData.ischangedpass=false;
		            		Log.d(LocalData.TAG_CHANGEPASS,"False");
		            		}
		            }
	            	if (mOJResponsive.getTag().equals(LocalData.TAG_REGISTER))
		            {	
		    	            Log.d(LocalData.TAG_REGISTER,"inside if");
		            	if (mOJResponsive.getSuccess()==true)
		            	{
		            		LocalData.isregisted = true;
		            		Log.d(LocalData.TAG_REGISTER,"ket qua register = true");
		            	}
		            	else 
		            	{
		            		LocalData.isregisted=false;
		            		Log.d(LocalData.TAG_REGISTER,"ket qua register =False");
		            		}
//		            	Intent intt = new Intent(ConnectService.this, Customdialog.class);
//			            intt.putExtra("mess", LocalData.strreceiver);
//			            intt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
//			           startActivity(intt);
		            }
	            	
	            }
	            catch(Exception e)
	            {
	            	Log.e(LocalData.TAG_LOGIN,""+e);
	            }
	            
	            //in the arrayList we add the messaged received from server
	            // notify the adapter that the data set has changed. This means that new message received
	            // from server was added to the list
	       
	        }
	    }

	 void alertmess(String mess) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(mess).setTitle("Thông báo").setCancelable(false)
					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							return;
						}
					});
			AlertDialog alert = builder.create();
			alert.show();
		}
		void alertfailmess(String mess) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(mess).setTitle("Thông báo").setCancelable(false)
					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
//							finish();
						}
					});
			AlertDialog alert = builder.create();
			alert.show();
		}
		
		
		public Authen check_tag(String receiver)
		{
			Authen mOJResponsive = new Authen();
			mOJResponsive = JSonparse.getauthen(receiver);
			return mOJResponsive;
			
		}
	public static void opendevice(Boolean status, int stt)
	{
		Log.d("Change device status1",""+stt+" " + status);
		if (status == true)
		{	
		try{
			DeviceItem newItemOpen = new DeviceItem();
			Log.d("Change device status1","Device ID: " + HomeControlActivity.mListDeviceMemberTop.get(3).getDeviceId() + " Name: " + HomeControlActivity.mListDeviceMemberTop.get(stt).getDeviceName());
			newItemOpen.setDeviceId(HomeControlActivity.mListDeviceMemberTop.get(stt).getDeviceId());
			newItemOpen.setDeviceStatus(1);
			sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
					newItemOpen, ListDeviceCardAdapterTop.handlerUpdateDevice);
			Log.d("Change device status1","End set: " + newItemOpen.getDeviceId() + " Name:" + newItemOpen.getDeviceName() +  " to "+ status);
		}
		catch(Exception e)
		{
			Log.e("Change device status1","failed: " + e);}
		}
		else 
		{	
		DeviceItem newItemOpen = new DeviceItem();
		Log.d("Change device status1","Device ID: " + HomeControlActivity.mListDeviceMemberTop.get(1).getDeviceId() + " Name: " + HomeControlActivity.mListDeviceMemberTop.get(stt).getDeviceName());
		newItemOpen.setDeviceId(HomeControlActivity.mListDeviceMemberTop.get(stt).getDeviceId());
		newItemOpen.setDeviceStatus(0);
		sendMessage.sendData(ActionMessage.UPDATE_DEVICE,
				newItemOpen, ListDeviceCardAdapterTop.handlerUpdateDevice);
		Log.d("Change device status1","End set: " + newItemOpen.getDeviceId() + " Name:" + newItemOpen.getDeviceName() + " to "+ status);
		}
		
	}
}

